<!-- 设备管理-设备页面 -->
<template>
  <div class="app-container" style="margin: 0">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="排查范围名称">
        <px-input v-model="queryParams.scopeName" placeholder="请输入排查范围名称" clearable />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>

    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button type="primary" icon="" @click="handleAdd">新增排查范围</px-button>
      </px-col>
    </px-row>

    <px-table
      v-if="!equipopen && !equipopenDetail"
      v-loading="loading"
      :data="typeList"
      height="calc(100vh - 369px)"
      show-overflow-tooltip
      border
      @selection-change="handleSelectionChange"
    >
      <px-table-column label="排查范围名称" prop="scopeName">
        <template #default="scope">
          <span>{{ scope.row.scopeName ? scope.row.scopeName : "-" }}</span>
        </template>
      </px-table-column>

      <px-table-column label="备注" prop="description">
        <template #default="scope">
          <span>{{ scope.row.description ? scope.row.description : "-" }}</span>
        </template>
      </px-table-column>

      <px-table-column label="创建人" width="160" prop="inboundDate">
        <template #default="scope">
          <span>{{ scope.row.inboundDate ? scope.row.inboundDate : "-" }}</span>
        </template>
      </px-table-column>

      <px-table-column label="创建时间" prop="createTime">
        <template #default="scope">
          <span>{{ scope.row.createTime ? scope.row.createTime : "-" }}</span>
        </template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="140">
        <template #default="scope">
          <px-button link type="primary" @click="handleDetail(scope.row.checkScopeId)">
            <px-tooltip class="box-item" content="详情" placement="top">
              <px-icon><Tickets /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" link type="primary" @click="handleEditor(scope.row.checkScopeId)">
            <px-tooltip class="box-item" content="编辑" placement="top">
              <px-icon><EditPen /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" link type="danger" @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon><Delete /></px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->

    <px-scrollbar v-if="equipopen" class="editorEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="cancel">返回</px-button>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">基本信息</div>
      <px-row style="padding: 20px">
        <px-col :span="24">
          <px-descriptions class="margin-top" :column="3" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">排查范围名称:</div>
              </template>
              {{ equipdata.scopeName }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
        <px-col :span="24">
          <px-descriptions class="center2" :column="3" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">排查范围说明:</div>
              </template>
              {{ equipdata.description }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
      </px-row>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">排查范围</div>
      <div style="padding: 0 20px 20px">
        <px-table style="margin-top: 20px" :data="equipdata.locations" height="480px" border>
          <px-table-column label="序号">
            <template #default="scope">
              <px-tooltip :content="scope.row.id" placement="top" effect="light">
                <span>{{ scope.$index + 1 || "--" }}</span>
              </px-tooltip>
            </template>
          </px-table-column>

          <px-table-column label="地点名称" prop="attributeName">
            <template #default="scope">
              <px-tooltip :content="scope.row.name" placement="top" effect="light">
                <span>{{ scope.row }}</span>
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
      </div>
    </px-scrollbar>
    <px-scrollbar v-if="equipopenDetail" class="addEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
      <px-form
        ref="detailruleFormRef"
        :disabled="fromdisable"
        :rules="rules"
        :model="equipdata"
        :inline="true"
        class="demo-form-inline"
        label-width="160px"
      >
        <div
          class="box-card1"
          :style="{
            height: jibenxinxiFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setqingdanFlg()">
            <div class="card-title">基本信息</div>
            <div class="card-main">
              <px-icon v-if="!jibenxinxiFlg"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="8">
                <px-form-item label="排查范围名称" prop="scopeName">
                  <px-input v-model="equipdata.scopeName" placeholder="请输入排查范围名称" clearable /> </px-form-item
              ></px-col>
            </px-row>
            <px-row>
              <px-col :span="24">
                <px-form-item label="排查范围说明" prop="description">
                  <px-input
                    v-model="equipdata.description"
                    style="width: calc(100% - 100px)"
                    :autosize="{ minRows: 5, maxRows: 6 }"
                    type="textarea"
                    placeholder="请输入排查范围说明"
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </div>
        <div
          class="box-card2"
          :style="{
            height: qingdanList == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setqingdanListFlg()">
            <div class="card-title">排查范围</div>
            <div class="card-main">
              <px-icon v-if="!qingdanList"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <div class="form-div" style="padding: 20px 32px">
            <px-button type="primary" plain @click="handledelAddPosition">添加地点</px-button>
            <px-button plain @click="handleDeleteAll">全部移除</px-button>
            <div class="form-table">
              <px-table style="margin-top: 20px" :data="equipdata.locations" height="480px" border>
                <px-table-column label="序号">
                  <template #default="scope">
                    <px-tooltip :content="scope.row.id" placement="top" effect="light">
                      <span>{{ scope.$index + 1 || "--" }}</span>
                    </px-tooltip>
                  </template>
                </px-table-column>

                <px-table-column label="地点名称" prop="attributeName">
                  <template #default="scope">
                    <px-tooltip :content="scope.row.name" placement="top" effect="light">
                      <span>{{ scope.row }}</span>
                    </px-tooltip>
                  </template>
                </px-table-column>
                <px-table-column v-if="!fromdisable" label="操作" align="center" width="280">
                  <template #default="scope">
                    <px-button link type="danger" @click="handleDeletePosition(scope.row)"
                      ><px-tooltip class="box-item" effect="light" content="删除" placement="top">
                        <px-icon><Delete /></px-icon> </px-tooltip
                    ></px-button>
                  </template>
                </px-table-column>
              </px-table>
            </div>
          </div>
          <px-dialog v-model="positionVisible" align-center title="添加地点" width="30%">
            <px-form :model="positionform">
              <px-form-item label="添加地点" label-width="70px">
                <px-tree-select
                  v-model="positionform.positionId"
                  clearable
                  style="width: 100%"
                  placeholder="请选择地点"
                  value-key="name"
                  :props="defaultProps"
                  :data="positionList"
                  check-strictly
                  :render-after-expand="false"
                />
              </px-form-item>
            </px-form>
            <template #footer>
              <span class="dialog-footer">
                <px-button @click="positionVisible = false">取消</px-button>
                <px-button type="primary" @click="savePosition"> 确认 </px-button>
              </span>
            </template>
          </px-dialog>
        </div>
      </px-form>
    </px-scrollbar>
    <div v-if="equipopenDetail" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button v-if="fromdisable" type="primary" @click="equipopenDetailcancel">关闭</px-button>
      <px-button v-else type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="equipopenDetailsubmitForm(detailruleFormRef)"
        >保存</px-button
      >
    </div>
  </div>
</template>

<script setup name="Dict" lang="ts">
// import useDictStore from '@/store/modules/dict'
defineOptions({
  name: "SystemDataDict"
});
const defaultProps = {
  children: "children",
  label: "name",
  value: "name"
};
const emits = defineEmits(["addDiv", "getTotal"]);
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";
import { scopequery, positionqueryTree, scopecreate, scopeupdate, scopegetById, scopedelete } from "@/api/scope";
const positionform = reactive({
  positionId: ""
});
const jibenxinxiFlg = ref(true);
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const jiqicanshuFlg = ref(true);
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const shebeitaizhangFlg = ref(true);
const setshebeitaizhangFlg = () => {
  shebeitaizhangFlg.value = !shebeitaizhangFlg.value;
};
const moxingshezhiFlg = ref(true);
const setmoxingshezhiFlg = () => {
  moxingshezhiFlg.value = !moxingshezhiFlg.value;
};
const qingdanList = ref(true);
const setqingdanListFlg = () => {
  qingdanList.value = !qingdanList.value;
};
const positionVisible = ref(false);
const handledelAddPosition = () => {
  positionform.positionId = "";
  positionVisible.value = true;
};
const savePosition = () => {
  if (positionform.positionId != "") {
    equipdata.value.locations.push(positionform.positionId);
    console.log(positionform.positionId);
    positionVisible.value = false;
  } else {
    PxMessage.error("请选择采集位号");
  }
};

const handleDeleteAll = row => {
  PxMessageBox.confirm("是否将列表中的地点全部移除？", "移除提示", {
    confirmButtonText: "确定移除",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      equipdata.value.locations = [];
    })
    .catch(() => {});
};
const route = useRoute();
onMounted(() => {
  if (route.query.equipmentId) {
    handleDetail(route.query.equipmentId);
  }
});
const { proxy }: any = getCurrentInstance();

const typeList = ref([]);
const detailruleFormRef = ref();
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);

// 图片是否上传完，是否可以保存
const savePhotoStatus1 = val => {
  console.log(val);
  photoStatusFlag.value = val;
};
const savePhotoStatus2 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus3 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus4 = val => {
  photoStatusFlag.value = val;
};

const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  storeList: [],
  sellList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  photoStatusFlag: false,
  fileStatusFlag: false,
  rediusList: [],
  equipdata: {
    checkScopeId: 0,
    scopeName: "",
    description: "",
    locations: [],
    createrId: ""
  },
  queryParams: {
    orderByColumn: "",
    isAsc: "",
    scopeName: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    scopeName: [{ required: true, message: "存排查范围名称不能为空", trigger: "blur" }]
    // description: [{ required: true, message: "排查范围说明不能为空", trigger: "blur" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false
});

const { liquidList, queryParams, form, rules, equipdata, equipmentTypeList, modelIdList, photoStatusFlag, fileStatusFlag, positionList, rediusList } =
  toRefs(data);

const getqueryCategoryList = () => {
  queryChildByTypeCodeAndItemValue({
    value: "CH01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    liquidList.value = response;
  });
  positionqueryTree({ pageNum: 1, pageSize: 10 }).then((response: any) => {
    positionList.value = response;
  });
};
getqueryCategoryList();
function getList() {
  loading.value = true;
  scopequery(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    total.value = response.total;
    emits("getTotal", response.total);
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  emits("addDiv", true);
  equipopen.value = false;
}
function equipopenDetailcancel() {
  emits("addDiv", true);
  equipopenDetail.value = false;
}
/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    scopeName: "",
    orderBy: ""
  };
  dateRange.value = [];
  handleQuery("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  emits("addDiv", false);
  buttonTitle.value = "新增";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipmentTypeList.value = [];
  modelIdList.value = [];
  equipdata.value = {
    checkScopeId: 0,
    scopeName: "",
    description: "",
    locations: [],
    createrId: ""
  };
}

const handleDetail = async val => {
  emits("addDiv", false);
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  const data = await scopegetById({ checkScopeId: val });
  //console.log(data);

  equipopen.value = true;
  // equipopenDetail.value = true;
  fromdisable.value = true;
  equipdata.value = data;
};

const handleEditor = async val => {
  emits("addDiv", false);
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;

  const data = await scopegetById({ checkScopeId: val });
  // console.log(data);
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipdata.value = data;
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 提交按钮 */

const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = {
        checkScopeId: equipdata.value.checkScopeId,
        scopeName: equipdata.value.scopeName,
        description: equipdata.value.description,
        locations: equipdata.value.locations,
        createrId: equipdata.value.createrId
      };
      if (buttonTitle.value == "新增") {
        scopecreate(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          equipopenDetail.value = false;
          emits("addDiv", true);
        });
      } else {
        scopeupdate(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          equipopenDetail.value = false;
          emits("addDiv", true);
        });
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  PxMessageBox.confirm('是否确认删除"' + row.scopeName + '"？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await scopedelete({ checkScopeId: row.checkScopeId });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

function handleDeletePosition(row) {
  PxMessageBox.confirm('是否确认删除"' + row.scopeName + '"？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      equipdata.value.locations = equipdata.value.locations.filter(item => item != row);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

getList();
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 100px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs__header) {
  // padding-left: 6px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

:deep(.px-upload-list--picture-card .px-upload-list__item) {
  width: 96px;
  height: 96px;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.center2 {
  :deep(.px-descriptions__body) {
    table {
      border-left: none;

      .is-bordered-label {
        border-top: none !important;
        border-left: none !important;
      }

      .is-bordered-content {
        border-top: none !important;
      }
    }
  }
}
</style>
